<?php
/**
 * 检测用户是否登录了
 *
 */
Class Hm_Controller_Plugin_CheckHasAccess Extends Zend_Controller_Plugin_Abstract
{

    /**
     * 分发前调用
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $config = Zend_Registry::get('config');
        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        $auth = $bootstrap->getResource('Auther');
        if (! $auth->hasIdentity()) {
            $user = new stdClass();
            $user->uid = 0;
            $user->username = 'Guest';
         } else {
            $user = $auth->getIdentity();
         }
        if(isset($config['ifuser_online_state'])&&$config['ifuser_online_state'] == 1){
             $onlineUserModel = new Model_OnlineUser();
             if($auth->hasIdentity()){
                 $currentUser = $onlineUserModel->find($user->uid);
                 if($currentUser){
                     if($currentUser->ip == $user->last_ip){
                         $currentUser->dateline = time();
                         $currentUser->save();
                     }else{//在另一地点登录
                         $auth->clearIdentity();
                         $user = new stdClass();
                         $user->uid = 0;
                         $user->username = 'Guest';
                     }
                 }else{//被强制离线了
                     $auth->clearIdentity();
                     $user = new stdClass();
                     $user->uid = 0;
                     $user->username = 'Guest';
                 }
             }
             //刷新其它用户
             $sessionTime = $config['user_session_time'];
             if($config['user_session_time'] == 0){
                 $sessionTime = 20;
             }
             $onlineUserModel->getTable()->delete(array('dateline < ?'=>time()-$sessionTime*60));
         }
         // 加载view
         $bootstrap->bootstrap('View');
         $view = $bootstrap->getResource('View');
         $view->user = $user;
         Zend_Registry::set('user',$user);

    }
}